package com.ttms.web.manage;
import com.ttms.pojo.*;
import com.ttms.service.PlayService;
import com.ttms.service.impl.PlayServiceImpl;
import com.ttms.utils.WebUtils;
import com.ttms.web.common.BaseServlet;
import com.google.gson.Gson;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class PlayServlet extends BaseServlet {

    /**
     * 处理分页功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数 pageNo 和 pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //2 调用playService.page(pageNo，pageSize)：Page对象
        PlayService playService = new PlayServiceImpl();
        List<PlayLang> playLangs = playService.queryPlayLangs();
        List<PlayType> playTypes = playService.queryPlayTypes();
        Page<Play> page = playService.page(pageNo,pageSize);
        page.setUrl("/ttms/manage/playServlet?action=page");
        //3 保存Page对象到Request域中

        for (PlayLang playLang:playLangs) {
            System.out.println(playLang.getPlay_lang_name());
        }
        req.setAttribute("page",page);
        req.setAttribute("playLangs", playLangs);
        req.setAttribute("playTypes", playTypes);
        //4 请求转发到pages/manager/p_manager.jsp页面
        req.getRequestDispatcher("/front-end/views/manage/playmanage.jsp").forward(req,resp);
    }

    protected void pageByName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数 pageNo 和 pageSize
        System.out.println("hello");
        String play_name = req.getParameter("play_name");
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
        //2 调用playService.page(pageNo，pageSize)：Page对象
        PlayService playService = new PlayServiceImpl();
        List<PlayLang> playLangs = playService.queryPlayLangs();
        List<PlayType> playTypes = playService.queryPlayTypes();
        Page<Play> page = playService.queryPlayByName(pageNo,pageSize,play_name);
        String url = "/ttms/manage/playServlet?action=pageByName&play_name=" +play_name;
        page.setUrl(url);
        //3 保存Page对象到Request域中

        req.setAttribute("page",page);
        req.setAttribute("playLangs", playLangs);
        req.setAttribute("playTypes", playTypes);
        //4 请求转发到pages/manager/p_manager.jsp页面
        req.getRequestDispatcher("/front-end/views/manage/playmanage.jsp").forward(req,resp);
    }

    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageNo = req.getParameter("pageNo");
        //1先 判 断 上 传 的 数 据 是 否 多 段 数 据 （ 只 有 是 多 段 的 数 据 ， 才 是 文 件 上 传 的 ）
        if (ServletFileUpload.isMultipartContent(req)) {
            //创 建 FileItemFactory工 厂 实 现 类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创 建 用 于 解 析 上 传 数 据 的 工 具 类 ServletFileUpload 类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            Map<String,Object> play = new HashMap<String, Object>();
            try {
                // 解 析 上 传 的 数 据 ， 得 到 每 一 个 表 单 项
                List<FileItem> list = servletFileUpload.parseRequest(req);
                // 循环判断每一个表单项是普 通 类 型 ， 还 是 上 传 的 文 件
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        // 普通表单项
                        play.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
//                        System.out.println("表单项的 name 属性值：" + fileItem.getFieldName());
                        // 参 数 UTF-8. 解 决 乱 码 问 题
//                        System.out.println("表单项的 value 属性值：" + fileItem.getString("UTF-8"));
                    } else {
                        // 上 传 的 文 件
                        System.out.println("表单项的 name 属性值：" + fileItem.getFieldName());
                        System.out.println("上传的文件名：" + fileItem.getName());
                        //获取上传文件名
                        String fileName = fileItem.getName();
                        //获取后缀名
                        String sname = fileName.substring(fileName.lastIndexOf("."));
                        //时间格式化格式
                        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmssSSS");
                        //获取当前时间并作为时间戳
                        String timeStamp=simpleDateFormat.format(new Date());
                        //拼接新的文件名
                        String newName ="play"+timeStamp+sname;
                        //保存当前文件路径
                        String path = "F:\\code\\ttms\\src\\main\\webapp\\front-end\\img\\" + newName;
                        System.out.println(path);
                        fileItem.write(new File(path));
                        String play_image = path;
                        play.put(fileItem.getFieldName(), "front-end/img/"+newName);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            PlayService playService = new PlayServiceImpl();
            List<PlayLang> playLangs = playService.queryPlayLangs();
            List<PlayType> playTypes = playService.queryPlayTypes();
            Play add = WebUtils.copyParamToBean(play,new Play());
            playService.addPlay(add);
        }
        resp.sendRedirect("/ttms/manage/playServlet?action=page&pageNo="+pageNo);
}


    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、获取请求的参数id
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
//        2、调用Service删除
        PlayService playService = new PlayServiceImpl();
        playService.deletePlayById(id);
//        3、重定向回管理页面
        resp.sendRedirect("/manage/playServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }



    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1 获取请求的参数编号
        if (ServletFileUpload.isMultipartContent(req)) {
            //创 建 FileItemFactory工 厂 实 现 类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            // 创 建 用 于 解 析 上 传 数 据 的 工 具 类 ServletFileUpload 类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            Map<String,Object> play = new HashMap<String, Object>();
            try {
                // 解 析 上 传 的 数 据 ， 得 到 每 一 个 表 单 项
                List<FileItem> list = servletFileUpload.parseRequest(req);
                // 循环判断每一个表单项是普 通 类 型 ， 还 是 上 传 的 文 件
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()) {
                        // 普 通 表 单 项
                        System.out.println(play);
                        play.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
                    } else {
                        // 上 传 的 文 件
                        //获取上传文件名
                        String fileName = fileItem.getName();
                        if (!(fileName.equals(null)&&fileName.equals(""))){
                            //获取后缀名
                            String sname = fileName.substring(fileName.lastIndexOf("."));
                            //时间格式化格式
                            SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmssSSS");
                            //获取当前时间并作为时间戳
                            String timeStamp=simpleDateFormat.format(new Date());
                            //拼接新的文件名
                            String newName ="play"+timeStamp+sname;
                            //保存当前文件路径
                            String path = "F:\\code\\ttms\\src\\main\\webapp\\front-end\\img" + newName;
                            System.out.println(path);
                            fileItem.write(new File(path));
                            String play_image = path;
                            play.put(fileItem.getFieldName(), "front-end/img/"+newName);
                            System.out.println(newName);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            Play update = WebUtils.copyParamToBean(play,new Play());
            PlayService playService = new PlayServiceImpl();
            Play oldplay = playService.queryPlayById(update.getPlay_id());
            String oldplay_image = oldplay.getPlay_image();
            String play_image = update.getPlay_image();
            if (play_image.equals("") || play_image.equals(null)){
                System.out.println("取原值");
                update.setPlay_image(oldplay_image);
                System.out.println(update.getPlay_image());
            }
            playService.updatePlay(update);
        }
        resp.sendRedirect("/ttms/manage/playServlet?action=page&pageNo=" + req.getParameter("pageNo"));
    }



    protected void getPlay(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1 获取请求的参数影片编号
        int id = WebUtils.parseInt(req.getParameter("id"), 0);
        System.out.println("查询的id为：" + id);
        //2 调用playService.queryPlayById查询影片
        PlayService playService = new PlayServiceImpl();
        Play play = playService.queryPlayById(id);
        play.setPlay_id(id);
        Gson gson = new Gson();
        String json = gson.toJson(play);
        System.out.println(json);
        resp.getWriter().write(json);
        resp.getWriter().write(json);
    }
}
